package com.kehao.leetcode.middle.sort_search;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

public class TopKFrequentSolution {
    public int[] topKFrequent(int[] nums, int k) {
        int[] result = new int[k];
        HashMap<Integer,Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }else {
                map.put(nums[i],1);
            }
        }
        ArrayList<int []> arrayList = new ArrayList<>();
        for (int i :map.keySet()) {
            int[] num = new int[2];
            num[0] = i;
            num[1] = map.get(i);
            arrayList.add(num);
        }
        arrayList.sort((num1,num2)->num2[1]-num1[1]);
        for (int i = 0; i < result.length; i++) {
            result[i] = arrayList.get(i)[0];
        }
        return result;
    }

    @Test
    public void test01(){
        int [] nums = {1,1,1,2,2,3};
        int k = 2;
        int[] result = topKFrequent(nums, k);
        Arrays.stream(result).forEach(i-> System.out.println(i));

    }
}
